<template>
  <div class="dialog-box" style="position: relative">
    <el-form
      class="filter-box"
      ref="formFlowSetClassStudentAIRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="90px"
      label-position="right"
      @submit.prevent
    >
      <!-- 过滤组件 -->
      <filter-box
        :item-width="350"
        @search="refreshFormFlowSetClassStudentAI()"
        @reset="resetFormFlowSetClassStudentAI"
      >
        <el-form-item label="学生姓名">
          <el-input
            class="filter-item"
            v-model="formFilter.studentNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="所属年级">
          <el-select
            class="filter-item"
            v-model="formFilter.gradeIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="gradeIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in gradeIdFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="经验等级">
          <el-select
            class="filter-item"
            v-model="formFilter.experienceLevelFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="experienceLevelFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in experienceLevelFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属校区">
          <dept-select class="filter-item" v-model="formFilter.schoolIdFilter" placeholder="" />
        </el-form-item>
        <template #operation>
          <el-button
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            :disabled="selectItemList.length <= 0"
            @click="onSubmit(true)"
          >
            添加
          </el-button>
        </template>
      </filter-box>
    </el-form>
    <!-- 选择表格 -->
    <table-box
      ref="studentClass"
      class="content-box page-table"
      :data="studentClassWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{ isCurrent: false, isHover: true }"
      :seq-config="{ startIndex: (studentClassWidgetCurrentPage - 1) * studentClassWidgetPageSize }"
      :sort-config="{ remote: true }"
      :hasExtend="false"
      :checkedMethod="rowChecked"
      @sort-change="studentClassWidget.onSortChange"
      @refresh="studentClassWidget.refreshTable()"
      @change="onStudentClassSelectionChange"
    >
      <vxe-column fixed="left" type="checkbox" :width="40" />
      <vxe-column
        title="序号"
        type="seq"
        fixed="left"
        :index="studentClassWidget.getTableIndex"
        :width="80"
      />
      <vxe-column title="学生姓名" field="studentName" />
      <vxe-column title="所属校区" field="schoolIdDictMap.name" />
      <vxe-column title="所属年级" field="gradeIdDictMap.name" />
      <vxe-column title="经验等级" field="experienceLevelDictMap.name" />
      <vxe-column title="注册时间" field="registerTime">
        <template v-slot="scope">
          <span>{{ formatDateByStatsType(scope.row.registerTime, 'day') }}</span>
        </template>
      </vxe-column>
      <template v-slot:empty>
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png" />
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            :total="studentClassWidgetTotalCount"
            :current-page="studentClassWidgetCurrentPage"
            :page-size="studentClassWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="studentClassWidget.onCurrentPageChange"
            @size-change="studentClassWidget.onPageSizeChange"
          >
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formFlowSetClassStudentAI',
};
</script>

<script setup lang="ts">
import { DialogProp } from '@/components/Dialog/types';
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import {
  treeDataTranslate,
  findItemFromList,
  findTreeNodePath,
  findTreeNode,
  stringCase,
} from '@/common/utils';
import { StudentData } from '@/api/generated/studentController';
import { StudentClassData } from '@/api/generated/studentClassController';
import { CourseData } from '@/api/generated/courseController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import {
  StudentController,
  StudentClassController,
  CourseController,
  SysDeptController,
} from '@/api/generated';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } =
  useUpload();
const {
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    // 数据源主表主键id字段
    classId?: ANY_OBJECT;
    // 是否在提交的时候调用后端接口保存数据，如果是false则代表这是一个级联表格的弹窗操作
    saveOnSubmit?: boolean;
    // 已经选中的数据
    selectIdList?: Array<string | number>;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    classId: undefined,
    saveOnSubmit: true,
    selectIdList: undefined,
    dialog: undefined,
  },
);

const formFlowSetClassStudentAIRef = ref();
// 表格已选中数据
const selectItemList = ref<StudentData[]>([]);
// 过滤值
const formFilter = reactive({
  // 学生姓名
  studentNameFilter: undefined,
  // 所属年级
  gradeIdFilter: undefined,
  // 经验等级
  experienceLevelFilter: undefined,
  // 所属校区
  schoolIdFilter: undefined,
});
const formFilterCopy = reactive({
  // 学生姓名
  studentNameFilter: undefined,
  // 所属年级
  gradeIdFilter: undefined,
  // 经验等级
  experienceLevelFilter: undefined,
  // 所属校区
  schoolIdFilter: undefined,
});
// 取消操作
const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  }
};
// 提交操作
const onSubmit = () => {
  if (!props.saveOnSubmit) {
    props.dialog?.submit(selectItemList.value);
    // 中间表字段映射
    selectItemList.value.forEach(row => {
      row.classStudent = {
        studentId: row.studentId,
      };
    });
    return;
  }
  let params: ANY_OBJECT = {
    classId: props.classId,
    classStudentDtoList: selectItemList.value.map(row => {
      return {
        studentId: row.studentId,
      };
    }),
  };

  StudentClassController.addClassStudent(params)
    .then(res => {
      ElMessage.success('添加成功');
      props.dialog?.submit(selectItemList.value);
    })
    .catch(e => {
      // TODO: 异常处理
    });
};

/**
 * 学校班级数据获取函数，返回Promise
 */
const loadStudentClassWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    classId: props.classId,
    studentDtoFilter: {
      searchString: formFilter.studentNameFilter,
      experienceLevel: formFilter.experienceLevelFilter,
      gradeId: formFilter.gradeIdFilter,
      schoolId: formFilter.schoolIdFilter,
    },
  };
  return new Promise((resolve, reject) => {
    StudentClassController.viewNotInClassStudentListFlowAddClass(params)
      .then(res => {
        // 级联更新设置临时唯一id
        let tempTime = new Date().getTime();
        resolve({
          dataList: res.data.dataList.map((item, index) => {
            return {
              __cascade_add_temp_id__: tempTime + index,
              ...item,
            };
          }),
          totalCount: res.data.totalCount,
        });
        selectItemList.value = [];
      })
      .catch(e => {
        reject(e);
      });
  });
};
/**
 * 学校班级数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadStudentClassVerify = () => {
  formFilterCopy.studentNameFilter = formFilter.studentNameFilter;
  formFilterCopy.gradeIdFilter = formFilter.gradeIdFilter;
  formFilterCopy.experienceLevelFilter = formFilter.experienceLevelFilter;
  formFilterCopy.schoolIdFilter = formFilter.schoolIdFilter;
  return true;
};
// 学校班级表格组件参数
const studentClassOptions: TableOptions<StudentData> = {
  loadTableData: loadStudentClassWidgetData,
  verifyTableParameter: loadStudentClassVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 学校班级表格组件
const studentClass = ref();
const studentClassWidget = useTable(studentClassOptions);
const {
  dataList: studentClassWidgetDataList,
  currentPage: studentClassWidgetCurrentPage,
  pageSize: studentClassWidgetPageSize,
  totalCount: studentClassWidgetTotalCount,
} = studentClassWidget;
// 表格行数据选中
const onStudentClassSelectionChange = (val: Array<StudentData>) => {
  selectItemList.value = val;
};
// 表格行数据是否允许选中
const rowChecked = ({ row: StudentData }) => {
  if (Array.isArray(props.selectIdList) && props.selectIdList.length > 0) {
    return props.selectIdList.indexOf(row.studentId) === -1;
  }
  return true;
};
/**
 * 所属年级下拉数据获取函数
 */
const loadGradeIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'Grade', itemIdType: 'Integer' })
      .then(res => {
        resolve({
          dataList: res.getList(),
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
// 所属年级配置参数
const gradeIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadGradeIdFilterDropdownList,
  isTree: false,
};
// 所属年级下拉组件
const gradeIdFilterWidget = useDropdown(gradeIdFilterOptions);
const { dropdownList: gradeIdFilterWidgetDropdownList } = gradeIdFilterWidget;
/**
 * 经验等级下拉数据获取函数
 */
const loadExperienceLevelFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ExpLevel', itemIdType: 'Integer' })
      .then(res => {
        resolve({
          dataList: res.getList(),
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
// 经验等级配置参数
const experienceLevelFilterOptions: DropdownOptions<DictData> = {
  loadData: loadExperienceLevelFilterDropdownList,
  isTree: false,
};
// 经验等级下拉组件
const experienceLevelFilterWidget = useDropdown(experienceLevelFilterOptions);
const { dropdownList: experienceLevelFilterWidgetDropdownList } = experienceLevelFilterWidget;
/**
 * 重置过滤值
 */
const resetFormFlowSetClassStudentAI = () => {
  formFilter.studentNameFilter = undefined;
  formFilterCopy.studentNameFilter = undefined;
  formFilter.gradeIdFilter = undefined;
  formFilterCopy.gradeIdFilter = undefined;
  formFilter.experienceLevelFilter = undefined;
  formFilterCopy.experienceLevelFilter = undefined;
  formFilter.schoolIdFilter = undefined;
  formFilterCopy.schoolIdFilter = undefined;
  refreshFormFlowSetClassStudentAI();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormFlowSetClassStudentAI();
};
const refreshFormFlowSetClassStudentAI = () => {
  // 刷新段落
  studentClassWidget.refreshTable();
};
const formInit = () => {
  gradeIdFilterWidget.onVisibleChange(true).catch(e => {
    console.error(e);
  });
  experienceLevelFilterWidget.onVisibleChange(true).catch(e => {
    console.error(e);
  });
  refreshFormFlowSetClassStudentAI();
};

onMounted(() => {
  // 初始化页面数据
  formInit();
});
</script>
